package com.ABdolphin.forum.services.impl;

import com.ABdolphin.forum.common.AppResult;
import com.ABdolphin.forum.common.ResultCode;
import com.ABdolphin.forum.dao.UserMapper;
import com.ABdolphin.forum.exception.ApplicationException;
import com.ABdolphin.forum.model.Board;
import com.ABdolphin.forum.model.User;
import com.ABdolphin.forum.services.IUserService;
import com.ABdolphin.forum.utils.MD5Util;
import com.ABdolphin.forum.utils.StringUtil;
import com.ABdolphin.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1,非空校验
        if(user==null || StringUtil.isEmpty(user.getUserName())
        ||StringUtil.isEmpty(user.getNickname())
        ||StringUtil.isEmpty(user.getPassword())
        ||StringUtil.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2,按用户名查询用户信息
        User existUser = userMapper.selectByUserName(user.getUserName());
        if (existUser!=null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //3,新增用户,设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setDeleteState((byte)0);
        user.setState((byte)0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);
        if (row!=1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功,userName={}",user.getUserName());


    }


    @Override
    public User selectByUserName(String userName) {
        if(StringUtil.isEmpty(userName)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(userName);
    }

    @Override
    public User login(String userName, String password) {
        if(StringUtil.isEmpty(password)||StringUtil.isEmpty(userName)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = selectByUserName(userName);
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString()+",userName"+userName);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString()+", 密码输入错误, userName"+userName);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info("登陆成功,username= "+userName);
        return user;
    }

    @Override
    public User selectById(Long id) {
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1,");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if (updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1,");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if(user==null||user.getId()==null||user.getId()<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if (existUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位,校验所有参数是否为空,防止用户传入的对象设置了其他属性,覆盖了没有校验的字段
        boolean checkAttr=false;
        User updateUser=new User();
        updateUser.setId(user.getId());
        if (!StringUtil.isEmpty(user.getUserName())
                &&!user.getUserName().equals(existUser.getUserName())){
            //需要更新用户名,进行唯一性校验
            User checkUser = userMapper.selectByUserName(updateUser.getUserName());
            if (checkUser!=null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUserName(user.getUserName());
            checkAttr=true;
        }
        //校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                &&!user.getNickname().equals(existUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
        //校验性别
        if (user.getGender()!=null
                &&existUser.getGender()!=user.getGender()){
            updateUser.setGender(user.getGender());
            if (updateUser.getGender()>2||updateUser.getGender()<0){
                updateUser.setGender((byte)2);
            }
            checkAttr=true;
        }
        //设置email
        if (!StringUtil.isEmpty(user.getEmail())
                &&!user.getEmail().equals(existUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
        //设置电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                &&!user.getPhoneNum().equals(existUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
        //校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                &&!user.getRemark().equals(existUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
        if (checkAttr==false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed("修改值与原先数据一致,请修改"));
        }
        //进行更新
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1,");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //校验
        if(id==null||id<=0||StringUtil.isEmpty(newPassword)
                ||StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null||user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed("原密码输入错误"));
        }
        //生成一个新的盐值
        String salt = UUIDUtil.UUID_32();
        String newEncryptPassword = MD5Util.md5Salt(newPassword, salt);

        User updateUser=new User();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(newEncryptPassword);
        Date date=new Date();
        updateUser.setUpdateTime(date);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1,");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }
}











